<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Home extends MY_Controller {
	

	var $userdata = array();
	
	public function __construct()
	{
		
		parent::__construct();
		
		if($this->session->userdata('customer_logged_in'))	
		{
			foreach($this->session->userdata as $k => $v)
			{
				$this->userdata[$k]	= $v;
			}
		}
		else
		{
		
			$restricted_methods = array('add_to_cart', 'add_booking');
			if(in_array($this->router->method, $restricted_methods))
				redirect('home/restricted');
		}
		
		$this->load->library('cart');
		if(isset($_SERVER['HTTP_REFERER']))
			$this->session->set_userdata('refered_from', $_SERVER['HTTP_REFERER']); 
	}
	
	public function index()
	{
		$this->layout_view = 'front-page';
		$this->title = 'Juro';
		
		$this->load->model('M_products');
		$this->data['featured'] = $this->M_products->getFeatured();
		$this->session->set_flashdata('refer', current_url());
			
	}
	
	public function about(){
		$this->title = 'About';
		
	}
	
	public function services_packages(){
		$this->title = 'Services and Packages';	
	}
	
	public function gallery(){
		$this->layout_view = 'front-page';
		$this->title = 'Gallery';	
		
		
	}
	public function location(){
		$this->title = 'location';	
	}
	
	public function feedback(){
		$this->title = 'Feedback';

		
		if($this->input->post('save')){
			$this->form_validation->set_rules('firstname', 'Firstname', 'required');
			$this->form_validation->set_rules('lastname', 'Lastname', 'required');
			$this->form_validation->set_rules('contact', 'Contact', 'required|numeric');
			$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
			$this->form_validation->set_rules('message', 'Message', 'required');
			
			if ($this->form_validation->run() == FALSE)
			{

			}
			else
			{
				$this->load->model('M_feedback');
				$customer = $this->input->post('firstname').' '.$this->input->post('lastname');
				$contact = $this->input->post('contact');
				$email = $this->input->post('email');
				$message = $this->input->post('message');
				if($this->M_feedback->add_feedback($customer, $contact, $email, $message))
				{
					set_redirect('success', 'Feed back sent', 'home/feedback');
				}
				else
				{
					set_redirect('error', 'Unable to send feedback at this moment please try again later.', 'home/feedback');
				}
				
			}
		}
			
	}
	
	
	public function login(){
		$this->title = 'Login';	
		
		if($this->input->post('login')){
		
			$this->load->model('M_users');
			$this->form_validation->set_rules('username', 'Username', 'required');
			$this->form_validation->set_rules('password', 'Password', 'required');
			if($this->form_validation->run() == FALSE){
			
			}
			else {
				$result = $this->M_users->verify_user((object) $this->input->post());
	
		
				if($result == 'user_verified')
					redirect('home/');
				else if($result == 'unverified')
					redirect('home/verify');
				else
					set_redirect('error', 'Invalid username/password combination', 'home/login');
			
			}
		}
	}
	
	public function verify(){
		$this->title = 'Verify';
		
		$this->load->model('M_users');
		
		if($this->input->post('verify')){
			$this->form_validation->set_rules('email', 'Email', 'required|email');
			
			if($this->form_validation->run() == FALSE){
			
			}
			else {
				$email = $this->M_users->getEmailAddress($this->input->post('email'));
				
				if($email){
					
					$enc_url = urlencode ($this->input->post('email'));
					$to = $this->input->post('email');
					$subject ="Confirm your account";
					$email = $this->input->post('email');
					$link = "<a href=http://jurosalon.com/home/verify_account/$enc_url>Verify</a>";
					
					$message = '<html><body>';
					$message .= "Hi $email! <br/><br/> Please click on the link below to verify your account <br/><br/>";
					$message .= " <br/><br/> $link";
					$message .= '</body></html>';
					
					$from = "admin@jurosalon.com";
					$headers = 'From: Confirm your account <'.$from.'>' . "\r\n";
					$headers .= "MIME-Version: 1.0\r\n";
					$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
					mail($to,$subject,$message,$headers);
					set_redirect('success', 'Email confirmation has been sent to '.$this->input->post('email'), 'home/verify');
				}
				else {
					set_redirect('error', 'We cannot find your email on the system, or that your email may have already been confirmed.', 'home/verify');
				}
			}
		}
	}
	
	public function verify_account(){
		
		$email = urldecode($this->uri->segment(3));
		
		$this->load->model('M_users');
		if($this->M_users->verifyEmailAddress($email)){
			$this->data['verified'] = TRUE;
			$row = $this->M_users->getIdFromEmail($email);
			$userdata = array(
						'userid' => $row->id,
						'username' => $row->username,
						'usertype' => $row->usertype,
						'firstname' => $row->firstname,
						'lastname' => $row->lastname,
						'contact' => $row->contact,
						'email' => $row->email,
						'customer_logged_in' => TRUE
					);
			$this->session->set_userdata($userdata);
		}
		else
			$this->data['verified'] = FALSE;
	}
	
	public function restricted(){
		$this->title = 'Restricted Access';	
		
	}
	
	public function verify_user()
	{
		if($this->input->post('login')){
			$this->form_validation->set_rules('username', 'Username', 'required');
			$this->form_validation->set_rules('password', 'Password', 'required');
			
			if ($this->form_validation->run() == FALSE)
			{
				$data = '';
				if(form_error('username'))
				$data = $data.'<span>'.form_error('username').'</span>';
				
				if(form_error('password'))
				$data = $data.'<span>'.form_error('password').'</span>';
				$this->session->set_flashdata('form_error', $data);
				redirect('home/'.$this->input->post('method'));
			}
			else
			{
				$this->load->model('M_users');
				
				if($this->M_users->verify_user((object) $this->input->post()))
					redirect('home/'.$this->input->post('method'));
				else{
					$data = array('form_error' => 'Invalid username/password');
					$this->session->set_flashdata($data);
					redirect('home/'.$this->input->post('method'));
				}
			
			}
			
				
		}
	}
	
	public function forgot_password(){
		$this->title = 'Forgot Password';
		
		$this->load->model('M_users');
		
		if($this->input->post('forgot')){
			$this->form_validation->set_rules('email', 'Email', 'required|email');
			
			if($this->form_validation->run() == FALSE){
			
			}
			else {
				$email = $this->M_users->checkEmailAddres($this->input->post('email'));
				$email = $email->email;
				
				if($email){
					$userid = $this->M_users->getIdFromEmail($email);
					$userid = $userid->id;
					$new_password = $this->generatePassword();
					$this->M_users->change_pass($new_password, $userid);
					$to = $email;
					$subject ="New Password";
					
					$message = '<html><body>';
					$message = "Hi $email! <br/><br/> Your password has been reset. <br/><br/> Please use this password to login to your account. Upon successful login you may want to change your password from there";
					$message = $message."<br/><br/> <h1>".$new_password."</h1>";
					$message .= '</body></html>';
					
					$from = "admin@jurosalon.com";
					$headers = 'From: New Account Password <'.$from.'>' . "\r\n";
					$headers .= "MIME-Version: 1.0\r\n";
					$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
					mail($to,$subject,$message,$headers);
					set_redirect('success', 'A new password has been sent to your email address', 'home/forgot_password');
				}
				else {
					set_redirect('error', 'We cannot find your email on the system.', 'home/forgot_password');
				}
			}
		}
	}
	
	public function register()
	{
		$this->title = 'Register';	
		if($this->input->post('register'))
		{
			$this->form_validation->set_rules('username', 'Username', 'required');
			$this->form_validation->set_rules('password', 'Password', 'required');
			$this->form_validation->set_rules('firstname', 'Firstname', 'required');
			$this->form_validation->set_rules('lastname', 'Lastname', 'required');
			$this->form_validation->set_rules('contact', 'Contact', 'required|integer');
			$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
			if ($this->form_validation->run() == FALSE)
			{
				
			}
			else
			{
				
				$this->load->model('M_users');
				if(!$this->M_users->checkUsernameEmail($this->input->post('username'), $this->input->post('email'))){
					
					$data = clean_post('register', $this->input->post());
					$data['usertype'] = 'customer';
	
					if($this->M_users->add_user($data))
					{
						$enc_url = urlencode ($this->input->post('email'));
						$to = $this->input->post('email');
						$subject ="Confirm your account";
						$email = $this->input->post('email');
						$link = "<a href=http://jurosalon.com/home/verify_account/$enc_url>Verify</a>";
						
						$message = '<html><body>';
						$message = "Hi $email! <br/><br/> Please click on the link below to verify your account <br/><br/>";
						$message = $message." <br/><br/> $link";
						$message .= '</body></html>';
						
						$from = "admin@jurosalon.com";
						$headers = 'From: Confirm your account <'.$from.'>' . "\r\n";
						$headers .= "MIME-Version: 1.0\r\n";
						$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
						mail($to,$subject,$message,$headers);
						set_redirect('success', 'You have registerd successfully! Check your email address on instructions on how to verify your account', 'home/registration_success');
					}
					else{
						set_redirect('error', 'Oops!, something happened please try again later.');
					}
					
				}
				else {
						set_redirect('error', 'Sorry but the username/email has already been taken.');
				}
				
			}
		}
	}
	
	public function registration_success()
	{
		$this->title = 'Registration successful!';	
		
		if($this->input->post('login')){
			$this->form_validation->set_rules('username', 'Username', 'required');
			$this->form_validation->set_rules('password', 'Password', 'required');
			
			if ($this->form_validation->run() == FALSE)
			{
				
			}
			else
			{
				$this->load->model('M_users');
				
				if($this->M_users->verify_user((object) $this->input->post()) == 'user_verfified')
					redirect('home/');
				else if($this->M_users->verify_user((object) $this->input->post()) == 'unverified')
					set_redirect('notice', 'Please verify your account first, An email has been sent to your email address with instructions on how to verify your account.');
				else
					set_redirect('error', 'Username/Password combination invalid', 'home/registration_success');	
			
			}
			
				
		}
	}
	
	public function my_account()
	{
		$this->title = 'My Account';
		$this->data['userdata'] = $this->userdata;
		$this->load->model('M_users');
		$this->data['user'] = $this->M_users->getUser($this->userdata['userid']);
	}
	
	public function edit_account()
	{
		$this->title = 'Edit Account';
		$this->data['userdata'] = $this->userdata;
		$this->load->model('M_users');
		$this->data['user'] = $this->M_users->getUser($this->userdata['userid']);
		
		if($this->input->post('save')){
			$this->form_validation->set_rules('firstname', 'Firstname', 'required');
			$this->form_validation->set_rules('lastname', 'Lastname', 'required');
			$this->form_validation->set_rules('contact', 'Contact', 'required|numeric');
			$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
			
			if ($this->form_validation->run() == FALSE)
			{

			}
			else
			{
				$data = clean_post('save', $this->input->post());
				if($this->M_users->updateUser($data, $this->userdata['userid']))
				{
					$new_userdata = array();
					$new_userdata['firstname'] = $data['firstname'];
					$new_userdata['lastname'] = $data['lastname'];
					$new_userdata['contact'] = $data['contact'];
					$new_userdata['email'] = $data['email'];
					$this->session->set_userdata($new_userdata);
					set_redirect('success', 'Account edited successfully', 'home/edit_account');
				}
				else
				{
					set_redirect('error', 'Unable to edit account at this moment please try again later.', 'home/edit_account');
				}
				
			}
		}
	}
	
	public function change_password()
	{
		$this->title = 'Change Password';
		$this->data['userdata'] = $this->userdata;
		
		if($this->input->post('save'))
		{
			$this->form_validation->set_rules('current_password', 'Current Password', 'required');
			$this->form_validation->set_rules('new_password', 'New Password', 'required');
			$this->form_validation->set_rules('r_new_password', 'Repeat New Password', 'required|matches[new_password]');
			
			if($this->form_validation->run() == FALSE)
			{
				
			}
			else
			{
				
				$this->load->model('M_users');	
				if($this->M_users->verify_password($this->input->post('current_password'), $this->userdata['userid']) == TRUE)
				{
					
					if($this->M_users->change_pass($this->input->post('new_password'),$this->userdata['userid']) == TRUE)
						set_redirect('success', 'Password changed successfully', 'home/change_password');
					else
						set_redirect('notice', 'Cannot change password at this moment please try again later.', 'home/change_password');
						
				}
				else
				{
					set_redirect('error', 'Your current password does not match the one our database', 'home/change_password');
				}	
			}
			
		}
	}
	
	public function products()
	{
		$this->title = 'Products';
		$this->load->model('M_products');
		$this->data['userdata'] = $this->userdata;
		$this->data['products'] = $this->M_products->getProducts();
	}
	
	public function featured_products(){
		$this->load->model('M_products');
		$this->data['featured'] = $this->M_products->getFeatured();
		$this->session->set_flashdata('refer', current_url());	
	}
	
	public function view_product(){
		$id = $this->uri->segment(3);
		$this->load->model('M_products');
		$this->data['p'] = $this->M_products->getProduct($id);
	}
	
	public function add_to_cart()
	{
		$id = $this->uri->segment(3);
		if(!$this->session->userdata('referred_from'))
			$this->session->set_userdata('referred_from', 'home/products');
		if($this->checkItem($id))
		{
			$c = $this->getCartItem($id);
			$c['qty']++;
			$data = array(
					'rowid' => $c['rowid'],
					'qty' =>  $c['qty']
					);	
			$this->cart->update($data);
			set_redirect('success', 'Item added to cart', $this->session->userdata('refered_from'));
		}
		else{
			$this->load->model('M_products');
			$p = $this->M_products->getProduct($id);
			
			if(!empty($p))
			{
				$c_data = array(
						'id' => $p->id,
						'name' => $p->name,
						'qty' => 1,
						'price' => $p->price,
						);
				$this->cart->insert($c_data);
				
				set_redirect('success', 'Item added to cart', $this->session->userdata('refered_from'));
			}
			
		}
		
		
		
	}
	
	public function my_cart()
	{
		$this->title = 'My Cart';
		$cfg['upload_path'] = './assets/images/proof';
		$cfg['allowed_types'] = 'gif|jpg|png';
		$cfg['max_size']	= '2048';
		$cfg['max_width']  = '1024';
		$cfg['max_height']  = '768';
		$this->load->library('upload', $cfg);
		
		$this->data['userdata'] = $this->userdata;
		if($this->input->post('update')){
			$this->cart->update($this->input->post('items'));
			set_redirect('success', 'Shopping cart updated successfully!', 'home/my_cart');
		}
		
		if($this->input->post('checkout')){
			
			if($_FILES['userfile']['error'] == 4)
				{
					set_redirect('error', 'Cannot process your request, please provide a proof of payment', 'home/my_cart');
				}
				else{
					
					if ($this->upload->do_upload())
					{
						$upload_data = $this->upload->data();
						$data['image'] = 'assets/images/proof/'.$upload_data['file_name'];
						
						$this->load->model('M_products');
						
						$order = array();
						$order['user_id'] = $this->session->userdata('userid');
						$order['proof'] = $data['image'];
						$order['status'] = 'Pending';
						$order['items'] = $this->cart->total_items();
						$order['total'] = $this->cart->total();
						$order['date'] = NOW;
						
						$order_details = array();
						
						foreach($this->cart->contents() as $c){
							$oo['product_id'] = $c['id'];
							$oo['qty'] = $c['qty'];
							$oo['total'] = $this->cart->format_number($c['subtotal']);
							$order_details[] = $oo;
						}
						
						
						
						if($this->M_products->addOrder($order, $order_details)){
							$this->cart->destroy();
							set_redirect('success', 'Checked out successfuly!, Please wait for us to verify your purchase', 'home/my_cart');
						}
						else{
							set_redirect('error', 'Cannot proceess your request, Please try again later', 'home/my_cart');	
						}
						
					}
					else
					{
					
						
					}
				

				}
				
		}
	}
	
	public function my_purchases(){
		$this->title = 'My Purchases';
		$this->data['userdata'] = $this->userdata;
		$this->load->model('M_products');
		
		$this->data['pp'] = $this->M_products->getCustomerPurchases($this->session->userdata('userid'));
		
	}
	
	public function view_purchase(){
		$order_id = $this->uri->segment(3);
		$this->title = 'View Purchase';	
		
		$this->data['userdata'] = $this->userdata;
		$this->load->model('M_products');
		$this->data['pp'] = $this->M_products->getPurchasedItems($order_id, $this->session->userdata('userid'));
	}
	
	public function cart_debug()
	{
		$id = $this->uri->segment(3);
		pre($this->getCartItem($id));
	}
	
	function checkItem($id)
	{
		if($this->cart->total_items() > 0){
			$in_array = FALSE;
			foreach($this->cart->contents() as $c)
			{
				if($c['id'] == $id)
					$in_array = TRUE;
				
			
			}
			return $in_array;
		}
		else
			return FALSE;
	}
	
	function getCartItem($id)
	{
		if($this->cart->total_items() > 0){
			$cart = array();
			foreach($this->cart->contents() as $c)
			{
				if($c['id'] == $id){
					$cart['rowid'] = $c['rowid'];
					$cart['qty'] = $c['qty'];
				}
							
			}
			return $cart;
		}
		else
			return FALSE;
	}
	
	public function my_bookings()
	{
		if($this->session->userdata('customer_logged_in'))
		{
			$this->load->model('M_bookings');
			$this->data['userdata'] = $this->userdata;
			$this->title = 'My appointments';
			$this->data['appointments'] = $this->M_bookings->getCustomerAppointments($this->userdata['userid']);
			
		}
		else
		{
			redirect('home');	
		}
	}
	
	public function delete(){
		$type = $this->uri->segment(3);	
		$id = $this->uri->segment(4);
		
		if($type == 'booking'){
			$this->load->model('M_bookings');
			
			$this->M_bookings->deleteBooking($id) ? set_redirect('success', 'Booking deleted', 'home/my_bookings') :set_redirect('error', 'Cannot delete booking', 'home/my_bookings');
		}
	}
	
	public function add_booking(){
		
		
		$this->title = 'Set appointment';
		$this->data['userdata'] = $this->userdata;
		$this->load->model('M_users');
		$this->data['stylists'] = $this->M_users->getUsers('stylist');
		
		
		
		if($this->input->post('set_appointment')){
			
			$this->form_validation->set_rules('time_id', 'Appointment Time', 'required');
			$this->form_validation->set_rules('stylistid', 'Stylist', 'required');
			$this->form_validation->set_rules('service', 'Service', 'required');
			$this->form_validation->set_rules('appointment_date', 'Appointment Date', 'required');
			
			if($this->form_validation->run() == FALSE){
					
			}
			else{
				$this->load->model('M_bookings');
				$data = clean_post('set_appointment', $this->input->post());
				if($this->M_bookings->addAppointment($data))
					set_redirect('success', 'Appointment added successfully!', 'home/add_booking');
				else
					set_redirect('error', 'Cannot set appointment, Please try again', 'home/add_booking');
			}
			
		}
		
	}
	
	public function schedule_appointment(){
		$id = $this->uri->segment(3);
		$this->title = 'Schedule appointment';	
		$this->data['userdata'] = $this->userdata;
		$this->load->model('M_users');
		$this->data['stylist'] = $this->M_users->getUser($id);
	}
	
	public function my_feedbacks()
	{
		$this->title = 'My Feedbacks';	
		$this->data['userdata'] = $this->userdata;
		$this->load->model('M_users');
		$this->data['stylist'] = $this->M_users->getUsers('stylist');
	}
	
	public function logout()
	{
		$this->session->sess_destroy();
		redirect('home/');	
	}
	
	public function debug_login()
	{
		$this->load->model('M_users');	
		$data['username'] = 'debug';
		$data['password'] = 'testing';
		if($this->M_users->verify_user((object) $data))
			echo 'true';
		else
			echo 'false';
	}
	
	public function chat(){
		$this->title = 'Chat';	
		$this->data['userdata'] = $this->userdata;
		
	
		$booking_id = $this->uri->segment(3);
		$s_id = $this->uri->segment(4);
		
		$userid = $this->session->userdata('userid');
		
		$this->load->model('M_users');
		
		$this->load->model('M_bookings');
		$booking = $this->M_bookings->getBooking($this->uri->segment(3));
		
		$datetime1 = date('Y-m-d H:i:s', strtotime($booking->adate.' '.$booking->aps_time_from));
		$current = new DateTime(date('Y-m-d H:i:s', strtotime(date('Y-m-d g:i A'))));

		$check1 = strtotime(date('Y-m-d H:i:s')) >= strtotime($booking->adate.' '.$booking->aps_time_from) ? TRUE : FALSE;
		$check2 = strtotime(date('Y-m-d H:i:s')) <= strtotime($booking->adate.' '.$booking->aps_time_to) ? TRUE : FALSE;
		
				
		if(!($check1 && $check2)){
			$this->data['disabled']	= TRUE;
		}
		
		
		$this->data['stylist'] = $this->M_users->getUser($s_id);
		$this->data['booking_id'] = $booking_id;
		$this->data['stylist_id'] = $s_id;
		
		
		
	}
	
	private function generatePassword($length = 8) {
    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $count = mb_strlen($chars);

    for ($i = 0, $result = ''; $i < $length; $i++) {
        $index = rand(0, $count - 1);
        $result .= mb_substr($chars, $index, 1);
    }

    return $result;
	}
	
}

?>